<?php

namespace App\Controllers\Diary;

use App\Models\Diary\Comment;
use App\Models\Diary\Diary;
use App\Models\Diary\CommentPra;

class AgreeZan extends \App\Libs\Base\BaseAction
{
    protected function beforeRun()
    {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }


    public function execute()
    {
        if (!$this->request->has('did')) {
            return \App\Libs\Views\Json::view(1, '失败：缺少日记ID', NULL);
        }
        $diaryId = $this->request->get('did');
		//查看用户是否评论过
		$commentPra = CommentPra::find(array(
			' did = :did: and uid = :uid:',
			'bind'=>array( 'did'=>$diaryId , 'uid'=>$this->session->user->id )
		));
		//查询日记信息
        $matchDiary = Diary::find([
            'conditions' => 'id=?1',
            'bind' => [1 => $diaryId]
        ]);
		if( empty( $commentPra ) ){
			//没有评论过
			$matchDiary->zan_num += 1;
			$commentPra = new CommentPra();
			$commentPra->uid = $this->session->user->id;
			$commentPra->did = $diaryId;
			$commentPra->ctime = date("Y-m-d H:i:s");
			$commentPra->show = 1;
		}else{
			//有过评论
			if( $commentPra->show == 1 ){
				$commentPra->show = 2;
				$matchDiary->zan_num -= 1;
			}else{
				$commentPra->show = 1;
				$matchDiary->zan_num += 1;	
			}
		}
        $zanres = $matchDiary->save();
        if ($zanres != false) {
			$commentPra->save();
            return \App\Libs\Views\Json::view(0, '点赞成功', NULL);
        } else {
            return \App\Libs\Views\Json::view(1, '系统繁忙，请稍后重试！', NULL);
        }


    }
}
